package com.tcm.pay.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.base.core.exception.ServiceException;
import com.base.core.utils.R;
import com.tcm.order.service.OrderService;
import com.tcm.pay.domain.dto.PaymentDTO;
import com.tcm.pay.enums.TradeTypeEnum;
import com.tcm.pay.service.OrderNotifyService;
import com.tcm.pay.service.PaymentService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

@DubboService(version = "0.0.1-alpha", group="order" , delay = -1, timeout = 6000)
public class OrderNotifyServiceImpl implements OrderNotifyService {

    @DubboReference(version = "0.0.1-alpha", check = false, timeout = 3000)
    OrderService orderService;

    @Autowired
    PaymentService paymentService;


    @Override
    public String alipay(String Succeed, String BillNo, String OrderNo, String payChannelNo) throws ServiceException {
        if (ObjectUtil.isNotNull(Succeed) && Succeed.equals("88")) {

            try {
                PaymentDTO p = paymentService.findByPaySn(BillNo, TradeTypeEnum.ORDER.getCode());
                if(ObjectUtil.isEmpty(p)){
                    return "fail";
                }
                if(p.getStatus().compareTo(new Byte("1")) == 0){
                    return "ok";
                }
                paymentService.updateStatusToPaid(p.getTargetId(),p.getDataId(),TradeTypeEnum.ORDER.getCode());
                orderService.changOrderPaid(p.getDataId());
            } catch (Exception e) {
                e.printStackTrace();
                R.throwFail(e.getMessage());
            }
            return "ok";
        }
        return "fail";
    }

    @Override
    public String wxpay(String Succeed, String BillNo, String OrderNo, String payChannelNo) throws ServiceException {
        System.out.println(Succeed+";"+BillNo);
        if (ObjectUtil.isNotNull(Succeed) && Succeed.equals("88")) {

            try {
                PaymentDTO p = paymentService.findByPaySn(BillNo, TradeTypeEnum.ORDER.getCode());
                if(ObjectUtil.isEmpty(p)){
                    return "fail";
                }
                if(p.getStatus().equals(new Byte("1"))){
                    return "ok";
                }
                paymentService.updateStatusToPaid(p.getTargetId(),p.getDataId(),TradeTypeEnum.ORDER.getCode());
                orderService.changOrderPaid(p.getDataId());
            } catch (Exception e) {
                e.printStackTrace();
                R.throwFail(e.getMessage());
            }
            return "ok";
        }
        return "fail";
    }
}
